package tech.eyao.hs60x.user.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import tech.eyao.hs60x.awareUtil.CommonServiceUtil;
import tech.eyao.hs60x.common.CommonConstants;
import tech.eyao.hs60x.common.ReturnCode;
import tech.eyao.hs60x.dto.AccountDTO;
import tech.eyao.hs60x.dto.BaseResult;
import tech.eyao.hs60x.dto.TokenDTO;
import tech.eyao.hs60x.enums.ExceptionCodeEnum;
import tech.eyao.hs60x.model.domain.AccountDO;
import tech.eyao.hs60x.service.AccountService;
import tech.eyao.hs60x.utils.RequestUtils;
import tech.eyao.hs60x.utils.TokenUtils;

@RestController
@RequestMapping("/user")
@Api("用户相关")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private AccountService      accountService;

    /**
     * 注册or登录
     * 
     * @param name
     * @return
     */
    @PostMapping("/otpLogin.do")
    @ApiOperation(value = "注册登录", notes = "",response = TokenDTO.class)
    public BaseResult otpLogin(@ApiParam(value = "手机号") String phone, @ApiParam(value = "验证码") String smsCode,
                                       @ApiParam(value = "账户类型(1：手机 2：设备)") Integer accountType,
                                       @ApiParam(value = "设备ID") String deviceId,
                                       @ApiParam("注册设备标的:1：Android 2：IOS 3：watch)") Integer deviceTag) {
        return accountService.otpLogin(phone, CommonConstants.DEFAULTPASSOWRD, deviceId, accountType, deviceTag,
                smsCode);
    }

    /**
     * 注销
     * 
     * @return
     */
    @PostMapping("/logout.do")
    @ApiOperation(value = "注销", notes = "根据token注销用户")
    public BaseResult logout() {
        return accountService.logout(RequestUtils.getRequest().getHeader(CommonConstants.REQUEST_HEADER_TOKE_NNAME));
    }

    /**
     * 账户详情
     * 
     * @return
     */
    @GetMapping("/getAccount.do")
    @ApiOperation(value = "查询账户详情,TODO 增加手表LBS信息 ", response = AccountDTO.class)
    public BaseResult getAccount() {
        return accountService.getAccountDetail(TokenUtils.getUserId());
    }

    /**
     * 获取watch信息
     * 
     * @param id
     */
    @PostMapping("/getWatchAccount.do")
    @ApiOperation(value = "查询手表端账户信息 TODO 增加绑定标记位",response=AccountDO.class)
    public BaseResult getWacthAccount(@ApiParam("手表账户ID") long watchId) {
        return accountService.getWacthAccount(TokenUtils.getUserId(), watchId);
    }

    /**
     * 上传用户头像
     */
	@PostMapping("/uploadImg.do")
    @ApiImplicitParam(name = "file", value = "上传用户头像", required = true, dataType = "MultipartFile")
    @ApiOperation(value = "上传头像")
    public BaseResult uploadImg(@RequestParam(value = "file") MultipartFile file) {
        if (null == file) {
            return BaseResult.isFailure(ExceptionCodeEnum.FILEUPLOAD_EXCEPTION.getCode(),
                    ExceptionCodeEnum.FILEUPLOAD_EXCEPTION.getMessage());
        }
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName + " 大小" + file.getSize());
        BaseResult result = null;
        try {
            String imgUrl = accountService.uploadImg(file.getBytes(),
                    RequestUtils.getRequest().getHeader(CommonConstants.REQUEST_HEADER_TOKE_NNAME));
            result = new BaseResult(ReturnCode.C_SUCCESS_CODE, ReturnCode.SUCCESS_CODE.getDesc());
            Map<String, String> map = new HashMap<>();
            map.put("avatar", imgUrl);
            result.data = map;
        } catch (IOException e) {
            logger.error("[UserController uploadImg error]", e);
        }

        return result;
    }

    /**
     * 编辑终端用户资料
     */
    @PostMapping("/editUserInfo.do")
    @ApiOperation(value = "编辑终端用户资料")
    public @ResponseBody BaseResult editUserInfo(@ApiParam(value = "设备USER信息DO") AccountDO accountDO) {
        try {
            //TODO 验证当前用户是否管理员
            if (!CommonServiceUtil.getInstance().checkUserCommonRole()) {
                return BaseResult.isBussinessFail("非管理员校色,无法修改当前设备信息！");
            }
            if (null == accountDO || 0 == accountDO.getId()) {
                return BaseResult.isBussinessFail("参数有误,请传入设备AID");
            }
            accountService.updateAccountByDo(accountDO);
        } catch (Exception e) {
            logger.error("[UserController editUserInfo error.]",e);
            return BaseResult.isDeFaultFailure();
        }
        return BaseResult.isSuccess();
    }
}
